package com.shop.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MessageConfig {
    public final static String Merchant_Exchange = "spring.merchant";
    public static final String PROCESS_QUEUE = "merchant1";

    public static final String TTL_QUEUE = "TTL_QUEUE";
    public static final String TTL_EXCHANGE = "TTL_EXCHANGE";
    public static final String TTL_QUEUE_EXCHANGE = "TTL_QUEUE_EXCHANGE";

    public static final String DLX_QUEUE = "DLX_QUEUE";
    public static final String DLX_EXCHANGE = "DLX_EXCHANGE";
    public static final String DLX_QUEUE_EXCHANGE = "DLX_QUEUE_EXCHANGE";

    //工作队列
    @Bean
    Queue processQueue() {
        return QueueBuilder.durable(PROCESS_QUEUE).build();
    }

    @Bean
    DirectExchange delayExchange() {
        return new DirectExchange(Merchant_Exchange);
    }

    @Bean
    Binding delayExchangeBingQueue(Queue processQueue, DirectExchange delayExchange) {
        return BindingBuilder.bind(processQueue).to(delayExchange).with(PROCESS_QUEUE);
    }

    //延时队列
    @Bean(TTL_QUEUE)
    Queue TTL_QUEUE() {
        Map<String,Object> arguments=new HashMap<>();
        arguments.put("x-message-ttl",900000);
        //arguments.put("x-message-ttl",10000);
        arguments.put("x-dead-letter-exchange",DLX_EXCHANGE);
        arguments.put("x-dead-letter-routing-key","dlx");
        return new Queue(TTL_QUEUE,true,false,false,arguments);
    }

    @Bean(TTL_EXCHANGE)
    TopicExchange TTL_EXCHANGE() {
        return new TopicExchange(TTL_EXCHANGE, true, false);
    }

    @Bean(TTL_QUEUE_EXCHANGE)
    Binding TTL_QUEUE_EXCHANGE(@Qualifier(TTL_QUEUE) Queue queue, @Qualifier(TTL_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("#.ttl.#").noargs();
    }

    //死信队列
    @Bean(DLX_QUEUE)
    Queue DLX_QUEUE() {
        return new Queue(DLX_QUEUE,true);
    }

    @Bean(DLX_EXCHANGE)
    TopicExchange DLX_EXCHANGE() {
        return new TopicExchange(DLX_EXCHANGE, true, false);
    }

    @Bean(DLX_QUEUE_EXCHANGE)
    Binding DLX_QUEUE_EXCHANGE(@Qualifier(DLX_QUEUE) Queue queue, @Qualifier(DLX_EXCHANGE) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("#.dlx.#").noargs();
    }

}
